<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="运营商" prop="agentId">
        <el-select :value="queryParams.userName" placeholder='请选择客户' :clearable='clearable' @clear="clearHandle" ref='chooseUserSearch'>
        <el-option :value="queryParams.userName" label="" style='height:200px;overflow-y: scroll;width: 100%;background: white;'>
				  <el-tree  :data="userList" :props="props" :accordion="accordion"  @node-click="handleNodeClick"></el-tree>
       </el-option>
				 </el-select>
      </el-form-item>
	    
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="子订单号" prop="subOrderNo">
        <el-input
          v-model="queryParams.subOrderNo"
          placeholder="请输入子订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="ICCID" prop="iccid">
        <el-input
          v-model="queryParams.iccid"
          placeholder="请输入ICCID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐名称" prop="pricingName">
        <el-input
          v-model="queryParams.pricingName"
          placeholder="请输入套餐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐编号" prop="pricingId">
        <el-input
          v-model="queryParams.pricingId"
          placeholder="请输入套餐编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="充值渠道" prop="depositChanl">
        <el-input
          v-model="queryParams.depositChanl"
          placeholder="请输入充值渠道"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
        <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable size="small">
          <el-option key="1" label="充值中" value="1"></el-option>
          <el-option key="2" label="已支付" value="2"></el-option>
        </el-select>
      </el-form-item>
      
       <el-date-picker
	      v-model="timevalue"
	      type="daterange"
	      range-separator="至"
	      start-placeholder="开始日期"
	      end-placeholder="结束日期">
	    </el-date-picker>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-document-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['whty:list:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['whty:list:export']"
        >导出</el-button>
      </el-col>
       <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click= 'delList'
          v-hasPermi="['whty:list:remove']"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="listList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="子订单号" align="center" prop="orderNo" />
      <el-table-column label="ICCID" align="center" prop="cardNo" />
      <el-table-column label="订单创建时间" align="center" prop="createTime" :formatter="timestampToTime" />
      <el-table-column label="企业名称" align="center" prop="userName" />
      <el-table-column label="套餐编号" align="center" prop="pricingId" />
      <el-table-column label="套餐名称" align="center" prop="pricingName" />
      <el-table-column label="充值金额（元）" align="center" prop="depositAmt" />
      <el-table-column label="购买数量" align="center" prop="count" />
      <el-table-column label="状态" align="center" prop="status" >
      	<template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status==1">待支付</el-tag>
          <el-tag type="success" v-if="scope.row.status==2">已支付</el-tag>
       </template> 
      </el-table-column>
      <el-table-column label="渠道" align="center" prop="depositChanl" />
      <!--<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['whty:list:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['whty:list:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充值订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
      	 <el-row>
          <el-col :span="12">
	           <el-form-item label="代理商" prop="userName">
	          	<el-input v-model="form.userName" placeholder="请输入代理商id" />
	        	</el-form-item>
          </el-col>
       	  <el-col :span="12">
       	  	<el-form-item label="企业用户" prop="enterpriseId">
         		 <el-input v-model="form.enterpriseId" placeholder="请输入企业用户" />
       		  </el-form-item>
        	</el-col>
        <el-col :span="12">
        	<el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
       	  </el-form-item>
        </el-col>
        <el-col :span="12">
        	<el-form-item label="子订单号" prop="subOrderNo">
          <el-input v-model="form.subOrderNo" placeholder="请输入子订单号" />
        	</el-form-item>
        </el-col>
    
        <el-col :span="12">
        	<el-form-item label="充值渠道" prop="depositChanl">
          <el-input v-model="form.depositChanl" placeholder="请输入充值渠道" />
        	</el-form-item>
        </el-col>
        <el-col :span="12">
        	<el-form-item label="充值金额" prop="depositAmt">
          <el-input v-model="form.depositAmt" placeholder="请输入充值金额" />
        	</el-form-item>
        </el-col>
       
        <el-col :span="12">
        	<el-form-item label="订单状态">
          <el-select v-model="form.status" placeholder="请选择订单状态" size="small">
          <el-option key="1" label="待支付" value="1"></el-option>
          <el-option key="2" label="已支付" value="2"></el-option>
       		</el-select>
        </el-form-item>
        </el-col>
    
    </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listList, getList, delList, addList, updateList, exportList,exportListiccids } from "@/api/order/sonList";
import {getUserList} from "@/api/order/list";
export default {
	 props:{
	   	 props: {
	      children: 'children',
	      label: 'label',
	    },
       	 /* 自动收起 */
	    accordion:{
	      type:Boolean,
	      default:()=>{ return false }
			},
			 /* 可清空选项 */
	    clearable:{
	      type:Boolean,
	      default:()=>{ return true }
			},
       },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      subOrderNos:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 充值订单表格数据
      listList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //用户列表
      userList:[],
      // 查询参数
      timevalue: undefined,//时间
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime1:undefined,  //开始时间
        endTime1:undefined,  //结束时间
        userName:undefined,
        iccid:undefined,
        agentId: undefined,
        enterpriseId: undefined,
        orderNo: undefined,
        subOrderNo: undefined,
        depositChanl: undefined,
        pricingName:undefined,
        pricingId:undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
  	 getUserList().then((res)=>{
    	this.userList = res.data.children;
    })
    this.getList();
  },
  methods: {
  	handleNodeClick(a){  //点击选着客户
  		console.log(a);
  		for(var key in a){
  			if(key=='agentId'){
  				this.queryParams.agentId = a[key]
  				this.queryParams.enterpriseId = undefined
  			}else if(key=='enterpriseId'){
  				this.queryParams.enterpriseId = a[key]
  				this.queryParams.agentId = undefined
  			}
  		}
  		this.queryParams.userName = a.label;
  		this.$refs.chooseUserSearch.blur();
  			console.log(this.queryParams)
  	},
  	clearHandle(){  //清楚选项
  		this.queryParams.userName = '';
  		this.queryParams.enterpriseId = undefined
  		this.queryParams.agentId = undefined
  	},
    /** 查询充值订单列表 */
    getList() {
      this.loading = true;
      listList(this.queryParams).then(response => {
        this.listList = response.rows;
        console.log(this.listList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      var timevalue = this.timevalue;
      if(timevalue){
      var startTime = new Date(timevalue[0]).getFullYear()+'-'+(new Date(timevalue[0]).getMonth()+1)+'-'+new Date(timevalue[0]).getDate();
      var endTime =  new Date(timevalue[1]).getFullYear()+'-'+(new Date(timevalue[1]).getMonth()+1)+'-'+new Date(timevalue[1]).getDate();
      this.queryParams.startTime1 = startTime;
      this.queryParams.endTime1 = endTime;
      }
      console.log(this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
    	this.timevalue = undefined;
    	this.queryParams=  {
        pageNum: 1,
        pageSize: 10,
        startTime1:undefined,  //开始时间
        endTime1:undefined,  //结束时间
        userName:undefined,
        msisdn:undefined,
        iccid:undefined,
        agentId: undefined,
        enterpriseId: undefined,
        orderNo: undefined,
        subOrderNo: undefined,
        depositChanl: undefined,
        pricingName:undefined,
        pricingId:undefined,
        status: undefined,
      }
       this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.subOrderNos = selection.map(item=>item.orderNo)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加充值订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      getList(id).then(response => {
      	response.data.status = JSON.stringify(response.data.status);
        this.form = response.data;
        console.log(this.form);
        this.open = true;
        this.title = "修改充值订单";
      });
    },
    delList(){  //批量删除
    	 this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idsStr = '';
		    	for(var i=0;i<this.ids.length;i++){
		    		idsStr+=this.ids[i]+','
		    	}
		    	delList(idsStr).then((res)=>{
		    		console.log(res);
		    		if(res.code==200){
		    			  this.$message({
			          message: '删除成功',
			          type: 'success'
			        });
			         this.queryParams.pageNum = 1;
     					 this.getList();
		    		}
		    	})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });	
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateList(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addList(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除充值订单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delList(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
    	var subOrderNosStr = '';
      let queryParams = this.queryParams;
     	queryParams.pageSize = null;
      queryParams.pageNum = null;
      if(this.subOrderNos.length>0){
      	for(var i=0;i<this.subOrderNos.length;i++){
      		subOrderNosStr+=this.subOrderNos[i]+','
      	}
      	queryParams = subOrderNosStr
      	this.$confirm('是否确认导出所有充值订单数据项?', "警告", {
	          confirmButtonText: "确定",
	          cancelButtonText: "取消",
	          type: "warning"
	        }).then(function() {
	          return exportListiccids(queryParams);
	        }).then(response => {
	          this.download(response.msg);
	        })
      }else{
	      	this.$confirm('是否确认导出所有充值订单数据项?', "警告", {
	          confirmButtonText: "确定",
	          cancelButtonText: "取消",
	          type: "warning"
	        }).then(function() {
	          return exportList(queryParams);
	        }).then(response => {
	          this.download(response.msg);
	        }).catch(function() {});
      }
    },
      timestampToTime (row, column) {
       var date = new Date(row.createTime) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear()
        var M = date.getMonth()+1 
        M = this.addZero(M);
        var D = date.getDate() 
         D = this.addZero(D);
        var h = date.getHours() 
          h = this.addZero(h);
        var m = date.getMinutes() 
          m = this.addZero(m);
        var s = date.getSeconds()
         s = this.addZero(s);
        return Y+'-'+M+'-'+D+' '+h+':'+m+':'+s
    },
     addZero(a){
    	return a = a<=9?'0'+a:a;
    },
  }
};
</script>